<script>
import { loginAPI, getUserInfoAPI } from '@/apis/sys'
import { useUserStore } from '@/stores/user'

export default {
  name: 'LoginIndex',
  data() {
    return {
      loginForm: {
        account: '',
        password: ''
      },
      loading: false,
      isFocused: {
        account: false,
        password: false
      }
    }
  },
  methods: {
    handleFocus(field) {
      this.isFocused[field] = true;
    },
    handleBlur(field) {
      this.isFocused[field] = false;
    },
    async handleLogin() {
      // 表单验证
      if (!this.loginForm.account || !this.loginForm.password) {
        alert('请输入账号和密码')
        return
      }

      this.loading = true
      try {
        // 调用登录接口
        const res = await loginAPI(this.loginForm)
        console.log('登录接口返回:', res);

        // 添加对res是否存在以及是否有code属性的检查
        if (res && res.code === 0) {
          // 登录成功，获取用户ID
          const userId = res.data && res.data.userId;
          console.log('当前登录用户ID:', userId);

          // 检查userId是否存在
          if (!userId) {
            throw new Error('用户ID不存在');
          }

          // 通过用户ID获取用户完整信息（包括基本信息、权限列表和角色列表）
          const userInfoRes = await getUserInfoAPI(userId);
          console.log('用户信息接口返回:', userInfoRes);
          
          // 添加对userInfoRes是否存在以及是否有code属性的检查
          if (userInfoRes && userInfoRes.code !== 0) {
            throw new Error(userInfoRes.msg || '获取用户信息失败');
          }
          
          // 检查userInfoRes.data是否存在
          if (!userInfoRes || !userInfoRes.data) {
            throw new Error('获取用户信息失败');
          }
          
          // 检查用户是否分配了角色
          const userRoles = userInfoRes.data.roles;
          if (!userRoles || userRoles.length === 0) {
            alert('该用户未分配角色，不能登录');
            this.loading = false;
            return;
          }
          
          // 保存用户信息到store
          const userStore = useUserStore()
          userStore.setUserInfo(userInfoRes.data)
          
          // 跳转到管理员主页
          this.$router.push('/admin')
        } else {
          // 登录失败，显示错误信息
          alert(res && res.msg || '登录失败')
        }
      } catch (error) {
        // 网络或其他异常
        console.error('登录失败:', error)
        alert('登录失败: ' + (error.msg || error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <div class="logo">
          <img src="@/assets/logo.svg" alt="Logo" class="logo-img">
        </div>
        <h1>系统登录</h1>
        <p>欢迎使用后台管理系统</p>
      </div>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group" :class="{ 'focused': isFocused.account, 'filled': loginForm.account }">
          <label for="account">账号</label>
          <input
            id="account"
            v-model="loginForm.account"
            type="text"
            @focus="handleFocus('account')"
            @blur="handleBlur('account')"
            placeholder=" "
            required
          />
        </div>
        <div class="form-group" :class="{ 'focused': isFocused.password, 'filled': loginForm.password }">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            @focus="handleFocus('password')"
            @blur="handleBlur('password')"
            placeholder=" "
            required
          />
        </div>
        <button type="submit" class="login-button" :disabled="loading">
          <span v-if="!loading">登 录</span>
          <span v-else class="loading-spinner"></span>
        </button>
      </form>
    </div>
    <div class="decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  right: -100px;
}

.circle-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  left: 100px;
}

.circle-3 {
  width: 150px;
  height: 150px;
  top: 200px;
  left: -50px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  transform: translateY(0);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
  z-index: 10;
}

.login-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.25);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.logo-img {
  width: 60px;
  height: 60px;
}

.login-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 600;
}

.login-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.login-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  position: relative;
  margin-bottom: 30px;
}

.form-group label {
  position: absolute;
  top: 50%;
  left: 15px;
  transform: translateY(-50%);
  font-size: 14px;
  color: #999;
  transition: all 0.3s ease;
  pointer-events: none;
  background: transparent;
  padding: 0 5px;
  z-index: 1;
}

.form-group input {
  width: 100%;
  padding: 15px 20px;
  border: 2px solid #e1e1e1;
  border-radius: 12px;
  font-size: 16px;
  background: transparent;
  outline: none;
  transition: border-color 0.3s ease;
  position: relative;
  z-index: 2;
}

.form-group input:focus {
  border-color: #667eea;
}

.form-group.focused label,
.form-group.filled label {
  top: 0;
  transform: translateY(-50%) scale(0.85);
  color: #667eea;
  background: white;
}

.form-group.focused input {
  border-color: #667eea;
}

.login-button {
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.6);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.loading-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
    margin: 0 15px;
  }
  
  .circle-1,
  .circle-2,
  .circle-3 {
    display: none;
  }
}
</style>